package com.tanglon.controller;

import com.tanglon.annotation.BlogLog;
import com.tanglon.config.RabbitMQConfig;
import com.tanglon.domain.ResponseResult;
import com.tanglon.domain.entity.ArticleViewMessage;
import com.tanglon.domain.entity.LoginUser;
import com.tanglon.service.ArticleService;
import com.tanglon.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

//    @GetMapping("/list")
//    public List<Article> test(){
//        return articleService.list();
//    }

    @GetMapping("/hotArticleList")
    @BlogLog(businessName = "查询热门文章")
    public ResponseResult hotArticleList(){
        //查询热门文章
        ResponseResult result=articleService.hotArticleList();
        return result;
    }

    @GetMapping("/articleList")
    @BlogLog(businessName = "首页文章信息")
    public ResponseResult articleList(Integer pageNum,Integer pageSize,Long categoryId){
        return articleService.articleList(pageNum,pageSize,categoryId);
    }

    @GetMapping("/{id}")
    @BlogLog(businessName = "获取文章详情")
    public ResponseResult getArticleDetail(@PathVariable("id") Long id){

        ResponseResult articleDetail = articleService.getArticleDetail(id);

        Long userId = null;
        userId = SecurityUtils.getUserId();

        ArticleViewMessage message = new ArticleViewMessage();
        message.setArticleId(id);
        message.setUserKey(userId);
        // 2. 异步发送消息，增加浏览量（非核心操作，异步化）
        try {
            // 发送消息到队列，文章ID作为消息内容
            rabbitTemplate.convertAndSend(
                    RabbitMQConfig.ARTICLE_VIEW_QUEUE,
                    message
            );
        } catch (Exception e) {
            // 即使消息发送失败，也不影响主流程，只是这次浏览不计数
            // 可以在这里记录日志，但不要抛出异常影响文章详情返回
            log.error("发送浏览量更新消息失败，文章ID: {}", message.getArticleId(), e);
        }
        return articleDetail;
    }

    @PutMapping("/updateViewCount/{id}")
    @BlogLog(businessName = "浏览量增加")
    public ResponseResult updateViewCount(@PathVariable("id") Long id){

        return articleService.updateViewCount(id);
    }

}
